﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;

namespace EasyComm
{
    public class ReflectionContext
    {
        public static List<Type> FindContractInterfaces(string assemblyPath)
        {
            List<Type> returnList = new List<Type>();
            Assembly templateAssembly = Assembly.LoadFrom(assemblyPath);
            Type[] interfaceList = templateAssembly.GetTypes();
            foreach (Type interfaceType in interfaceList)
            {
                if (!interfaceType.IsPublic || !interfaceType.IsInterface)
                {
                    continue;
                }
                object[] contractAttribute = interfaceType.GetCustomAttributes(typeof(ServiceContractAttribute), false);
                if (contractAttribute.Length > 0)
                {
                    returnList.Add(interfaceType);
                }
            }
            return returnList;
        }

        public static Type FindService(Type serviceContract)
        {
            Type[] typeList = serviceContract.Assembly.GetTypes();
            foreach (Type type in typeList)
            {
                if (!type.IsPublic)
                {
                    continue;
                }
                Type[] interfaceList = type.GetInterfaces();
                if (interfaceList.Count(item => item.FullName == serviceContract.FullName) == 0)
                {
                    continue;
                }
                return type;
            }
            return null;
        }
    }
}
